const qiniu = require("qiniu");
const path = require("path");
const url = require("url");
const moment = require("moment");

// 默认参数
const formatParam = (file, mdFileName, remotePath, prefixDir) => {
  const dt = new Date();
  const y = dt.getFullYear();
  const m = dt.getMonth() + 1;
  const d = dt.getDate();
  const h = dt.getHours();
  const mm = dt.getMinutes();
  const s = dt.getSeconds();

  const date = `${y}${m}${d}`;
  var ext = path.extname(file);

  let fileName = path.basename(file, ext);

  // 当是 ${fileName} 2024-03-05-14-13-12 文件名时，
  // 默认上传目录为 `${prefixDir}${filePrefixDir}/${timeFileName}: images/2024-03-05/14-13-12.png
  if (remotePath === '${fileName}') {
    const fileTime = moment(fileName.split('-')).subtract(1,'months');
    const filePrefixDir = fileTime.format("Y-MM-DD");
    const timeFileName =  fileTime.format("HH-mm-ss");
    fileName = !prefixDir ? `${filePrefixDir}/${timeFileName}` : `${prefixDir}${filePrefixDir}/${timeFileName}`
  } else {
    fileName = !prefixDir
      ? path.basename(file, ext)
      : `${prefixDir}${path.basename(file, ext)}`
  }

  return {
    date,
    dateTime: `${date}${h}${mm}${s}`,
    fileName,
    ext,
    mdFileName,
  };
};

const formatString = (tplString, data) => {
  const keys = Object.keys(data);
  const values = keys.map((k) => data[k]);

  return new Function(keys.join(","), "return `" + tplString + "`").apply(
    null,
    values
  );
};

module.exports = (config, file, mdFile) => {
  const {
    access_key,
    secret_key,
    bucket,
    domain,
    prefixDir = "",
    remotePath,
    zone = "Zone_z0",
    useHttpsDomain = true,
    useCdnDomain = true,
  } = config;

  // 创建鉴权对象
  const mac = new qiniu.auth.digest.Mac(access_key, secret_key);
  // 设置上传管理器
  const qiniuConfig = new qiniu.conf.Config();
  qiniuConfig.zone = qiniu.zone[zone]; // 根据需要选择合适的区域, 默认华东
  qiniuConfig.useHttpsDomain = useHttpsDomain; // 是否使用 https 域名
  qiniuConfig.useCdnDomain = useCdnDomain; // 上传是否使用cdn加速
  const formUploader = new qiniu.form_up.FormUploader(qiniuConfig);

  let localFile = file;
  if (/^".+"$/.test(localFile)) {
    localFile = file.substring(1, file.length - 1);
  }

  // 预设参数值
  const param = formatParam(localFile, mdFile, remotePath, prefixDir);
  //上传到七牛后保存的文件名
  const saveFile = formatString(remotePath + "${ext}", param);

  // 生成上传凭证
  const options = {
    scope: bucket + ":" + saveFile, // 指定上传到的目标文件夹
  };
  const putPolicy = new qiniu.rs.PutPolicy(options);

  // 生成上传 Token
  const uploadToken = putPolicy.uploadToken(mac);

  return new Promise((resolve, reject) => {
    const putExtra = new qiniu.form_up.PutExtra();
    formUploader.putFile(
      uploadToken,
      saveFile,
      localFile,
      putExtra,
      (err, { key }) => {
        if (!err) {
          // 上传成功， 处理返回值
          resolve({
            name: path.basename(key, param.ext),
            url: url.resolve(domain, saveFile),
          });
        } else {
          // 上传失败， 处理返回代码
          reject(err);
        }
      }
    );
  });
};
